<template>
  <!-- 查询表单 -->
  <el-form :model="logForm" :inline="true">
    <el-form-item label="管理员账号">
      <el-input v-model="logForm.username" style="width: 150px;" placeholder="请输入管理员账号" />
    </el-form-item>
    <el-form-item label="操作时间范围">
      <el-date-picker v-model="logForm.date" clearable type="datetimerange" value-format="YYYY-MM-DD HH:mm:ss"
        placeholder="选择时间范围" range-separator="至" start-placeholder="开始时间" end-placeholder="结束时间"
        style="width: 350px; margin-left: 10px"></el-date-picker>
    </el-form-item>
    <el-form-item label="管理员权限身份">
      <el-select v-model="logForm.rights" style="width: 120px;" placeholder="请选择">
        <el-option label="无权管理员" value="0"></el-option>
        <el-option label="有权管理员" value="1"></el-option>
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="getLogMessages">查询</el-button>
      <el-button type="info" @click="clearLogForm">清空</el-button>
    </el-form-item>
  </el-form>
  <div style="justify-content: space-between;margin-top: 10px;">
    <el-button type="danger" @click="batchDeleteLogs">批量删除</el-button>
  </div>
  <!-- 操作日志信息表格 -->
  <el-table :data="tableData" border style="width: 100%;margin-top: 10px;"
    @selection-change="getLogMessagesBySelectedId">
    <el-table-column type="selection" width="40" />
    <el-table-column type="index" label="id" width="50" />
    <el-table-column property="account" label="管理员账号" width="100" />
    <el-table-column property="rights" label="管理员权限身份" width="125" />
    <el-table-column property="operateTime" label="操作时间" width="180">
      <template #default="scope">
        {{ moment(scope.row.operateTime).format('YYYY-MM-DD HH:mm:ss') }}
      </template>
    </el-table-column>
    <el-table-column property="className" label="执行方法所在的类名" width="200" />
    <el-table-column property="methodName" label="执行的方法名" width="130" />
    <el-table-column property="methodParams" label="方法参数" width="115">
      <template #default="scope">
        <el-tooltip class="item" effect="dark" :content="scope.row.methodParams" placement="top">
          <span v-if="scope.row.methodParams">{{
            scope.row.methodParams.length > 10? scope.row.methodParams.slice(0, 10) + '...' :
              scope.row.methodParams}}</span>
        </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column property="resultValue" label="方法返回结果" width="115">
      <template #default="scope">
        <el-tooltip class="item" effect="dark" :content="scope.row.resultValue" placement="top">
          <span v-if="scope.row.resultValue">{{
            scope.row.resultValue.length > 10 ? scope.row.resultValue.slice(0, 10) + '...' :
              scope.row.resultValue}}</span>
        </el-tooltip>
      </template>
    </el-table-column>
    <el-table-column property="costTime" label="执行时间/毫秒" width="115" />
    <el-table-column label="操作">
      <template #default="scope">
        <el-link type="danger" @click="deleteLog(scope.row.id)">删除</el-link>
      </template>
    </el-table-column>
  </el-table>
  <!-- 操作日志分页组件 -->
  <div style="margin-top: 10px;">
    <el-pagination v-model:current-page="currentPageLog" v-model:page-size="pageSizeLog" :page-sizes="[5, 10, 15, 20]"
      :size="size" :disabled="disabled" :background="background" layout="total, sizes, prev, pager, next, jumper"
      :total="totalLog" @size-change="handleSizeChangeLog" @current-change="handleCurrentChangeLog" />
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from 'vue';
import { ElMessage } from 'element-plus';
import type { ComponentSize, FormInstance } from 'element-plus';
import axios from '@/utils/request';
import moment from 'moment';

// 组件相关设置及数据定义
const size = ref<ComponentSize>('default');
const currentPageLog = ref(1);
const pageSizeLog = ref(10);
const disabled = ref(false);
const tableData = ref([]);
const background = ref(true);
const totalLog = ref(0);
const logForm = ref({ username: '', date: ['', ''], rights: '' });
const logMessages = ref([]);
const logMessagesId = ref<number[]>([]);

// 获取选中操作日志信息id
const getLogMessagesBySelectedId = (selectedRows: any) => {
  logMessages.value = selectedRows;
  logMessagesId.value = [];
  selectedRows.forEach((row) => logMessagesId.value.push(row.id));
}

// 清空操作日志表单
const clearLogForm = () => {
  logForm.value.username = '';
  logForm.value.date = ['', ''];
  logForm.value.rights = '';
  getLogMessages();
}

// 操作日志分页相关逻辑
const refreshLogData = () => getLogMessages();
const handleSizeChangeLog = (val: number) => {
  pageSizeLog.value = val;
  refreshLogData();
}
const handleCurrentChangeLog = (val: number) => {
  currentPageLog.value = val;
  refreshLogData();
}

// 组件挂载时获取初始数据
onMounted(() => {
  getLogMessages();
})

// 获取操作日志信息
const getLogMessages = async () => {
  try {
    const result = await axios.get(`/admin/adminOperationLogs?page=${currentPageLog.value}&pageSize=${pageSizeLog.value}&username=${logForm.value.username}
      &startTime=${logForm.value.date[0]}&endTime=${logForm.value.date[1]}&rights=${logForm.value.rights}`);
    if (result.data.code === 1) {
      tableData.value = result.data.data.rows;
      totalLog.value = result.data.data.total;
      if (logForm.value.username || logForm.value.rights || logForm.value.date[0] || logForm.value.date[1]) {
        ElMessage.success('查询成功');
      }
    } else {
      ElMessage.error('获取日志信息失败');
    }
  } catch (error: any) {
    console.error('获取日志信息时发生错误:', error);
    if (error.response && error.response.status) {
      ElMessage.error(`获取日志信息时发生错误，状态码：${error.response.status}，请检查网络或联系后台管理员`);
    } else {
      ElMessage.error('获取日志信息时发生网络错误，请检查网络或联系后台管理员');
    }
  }
}

// 批量删除操作日志
const batchDeleteLogs = async () => {
  if (logMessagesId.value.length === 0) {
    ElMessage.error('请选择要删除的日志');
    return;
  }
  const isConfirmed = window.confirm('确认要批量删除所选日志吗？');
  if (!isConfirmed) {
    return;
  }
  try {
    const result = await axios.delete(`/admin/adminOperationLogs/${logMessagesId.value.join(',')}`);
    if (result.data.code === 1) {
      ElMessage.success('批量删除操作成功');
      getLogMessages();
    } else {
      ElMessage.error('批量删除操作失败');
    }
  } catch (error: any) {
    console.error('批量删除操作失败:', error);
    ElMessage.error('批量删除操作失败，请检查网络或联系后台管理员');
  }
}

// 删除单条操作日志
const deleteLog = async (id: number) => {
  const isConfirmed = window.confirm('确认要删除该条日志吗？');
  if (!isConfirmed) {
    return;
  }
  try {
    const result = await axios.delete(`/admin/adminOperationLogs/${id}`);
    if (result.data.code === 1) {
      ElMessage.success('删除操作成功');
      getLogMessages();
    } else {
      ElMessage.error('删除操作失败');
    }
  } catch (error: any) {
    console.error('删除操作失败:', error);
    ElMessage.error('删除操作失败，请检查网络或联系后台管理员');
  }
}
</script>

<style scoped></style>